<script context="module">
  export async function preload(page, session) {
    if (!session.user) {
      this.error(403, "对不起，请登录之后再查看本页面！");
      return;
    }
    let { p } = page.query;
    if (!p) {
      p = 1;
    }
    p = parseInt(p);
    const response = await Promise.all([
      this.fetch("/api2/getcategories"),
      this.fetch(`/api2/gettorrents?page=${p}&limit=24`),
    ]);
    const categories = await response[0].json();
    const torrents = await response[1].json();
    return { categories, torrents, p, user: session.user };
  }
</script>

<script>
  import { goto, stores } from "@sapper/app";
  import config from "./_config";
  import Pagination from "../components/Pagination.svelte";
  import dayjs from "dayjs";
  import relativeTime from "dayjs/plugin/relativeTime";
  import "dayjs/locale/zh-cn";
  import { toast } from "@zerodevx/svelte-toast";
  dayjs.extend(relativeTime);
  dayjs.locale("zh-cn");
  const { preloading, page, session } = stores();
  let path;
  $: path = $page.path;
  export let categories;
  export let torrents;
  let per_page = 24;
  export let p;
  export let user;
  async function changePage(evt) {
    const current = evt.detail;
    goto("/discover?p=" + current);
  }
  async function deleteTorrent(id) {
    const response = await fetch("/api2/deletetorrent?id=" + id, {
      method: "DELETE",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    });
    const parsed = await response.json();
    if (parsed.success == 0) {
      toast.push(parsed.message);
    } else {
      toast.push("删除成功，有10分钟缓存，请稍候再查看列表！");
    }
  }
  var bytesToSize = function (bytes) {
    if (isNaN(bytes)) {
      return "";
    }
    var symbols = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
    var exp = Math.floor(Math.log(bytes) / Math.log(2));
    if (exp < 1) {
      exp = 0;
    }
    var i = Math.floor(exp / 10);
    bytes = bytes / Math.pow(2, 10 * i);

    if (bytes.toString().length > bytes.toFixed(2).toString().length) {
      bytes = bytes.toFixed(2);
    }
    return bytes + " " + symbols[i];
  };
</script>

<svelte:head>
  <title>资源中心 - magnet-vip</title>
</svelte:head>
<div class="content">
  <div class="row">
    <div
      class="mx-1 my-1 px-2 py-1 {path == '/discover'
        ? 'bg-info'
        : 'bg-primary'} rounded"
    >
      <a class="text-white text-decoration-none text-tag" href="/discover"
        >全部</a
      >
    </div>
    {#each categories.categories as category}
      <div
        class="mx-1 my-1 px-2 py-1 {path == '/category/' + category._id
          ? 'bg-info'
          : 'bg-primary'} rounded"
      >
        <a
          class="text-white text-decoration-none text-tag"
          href="/category/{category._id}">{category.title}</a
        >
      </div>
    {/each}
  </div>
  <div class="row mt-4">
    <table class="table table-hover">
      <thead>
        <tr>
          <th class="magnet-th" scope="col">分类</th>
          <th scope="col">名称</th>
          <th class="d-none d-md-table-cell magnet-th" scope="col">大小</th>
          <th class="magnet-th" scope="col">链接</th>
          <th class="d-none d-md-table-cell magnet-th" scope="col">日期</th>
        </tr>
      </thead>
      <tbody>
        {#each torrents.torrents as torrent}
          <tr>
            <td>{torrent.category ? torrent.category.title : "未分类"}</td>
            <td
              ><a href="/torrent/{torrent._id}" title={torrent.name}
                >{torrent.name}</a
              >
              {#if user.isadmin}
                <button
                  class="btn btn-danger btn-small"
                  on:click={deleteTorrent(torrent._id)}>删除</button
                >
              {/if}
            </td>
            <td class="d-none d-md-table-cell">{bytesToSize(torrent.length)}</td
            >
            <td>
              <a
                href="{config.host}/api2/download/{torrent.infoHash}"
                target="_blank"
              >
                <i class="fas fa-download" />
              </a>
              <a href={torrent.magnet} target="_blank">
                <i class="fas fa-magnet" />
              </a>
            </td>
            <td class="d-none d-md-table-cell">
              {dayjs().from(dayjs(torrent.meta.createAt))}
            </td>
          </tr>
        {/each}
      </tbody>
    </table>
  </div>
  <div class="d-flex justify-content-center mb-4">
    <Pagination
      rounded
      bind:current={p}
      num_items={torrents.counts}
      {per_page}
      on:navigate={changePage}
    />
  </div>
</div>
